package com.ced.sip.system.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;


import com.ced.base.action.BaseAction;
import com.ced.base.exception.BaseException;
import com.ced.base.utils.GlobalSettingBase;
import com.ced.sip.common.AttachmentStatus;
import com.ced.sip.common.UserRightInfoUtil;
import com.ced.sip.common.WebMenu;
import com.ced.sip.common.WebMenuList;
import com.ced.sip.common.biz.IAttachmentBiz;
import com.ced.sip.common.entity.Attachment;
import com.ced.sip.common.utils.DateUtil;
import com.ced.sip.common.utils.StringUtil;
import com.ced.sip.system.biz.IWebInfoBiz;
import com.ced.sip.system.entity.WebInfo;

@SuppressWarnings("serial")
public class WebInfoAction extends BaseAction {
    //上传文件存放路径   
    private final static String UPLOADDIR = "upload/webInfo/";
	private IWebInfoBiz iWebInfoBiz;
	private IAttachmentBiz iAttachmentBiz;
	
	private WebInfo webInfo;

	private WebMenuList webMenuList=new WebMenuList();
	private List<WebMenu> webMenus;

	private File file;
	
	private String fileContentType;   
	
	private String fileFileName; 
	
	private File fileLocation;
	/**
	 * 查看网站信息列表
	 * 
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String viewWebInfo() throws BaseException {

		try {
			
		} catch (Exception e) {
			log.error("查看网站信息列表错误！", e);
			throw new BaseException("查看网站信息列表错误！", e);
		}

		return VIEW;

	}

	/**
	 * 查看网站信息列表
	 * 
	 * @return
	 * @throws BaseException
	 * @Action
	 */
	public String findWebInfo() throws BaseException {

		try {
			
			if(webInfo==null)
			{
				webInfo=new WebInfo();
			}
			String publishDate=this.getRequest().getParameter("publishDate");
			
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
			  
			if(StringUtil.isNotBlank(publishDate))
			{
				webInfo.setPublishDate(sdf.parse(publishDate));
			}
			String title=this.getRequest().getParameter("title");
			webInfo.setTitle(title);
			
			List<WebInfo> president = this.iWebInfoBiz.getWebInfoList(this.getRollPageDataTables(), webInfo); 
			for(WebInfo webInfo:president){
				webInfo.setWmName(webMenuList.getWebMenu(webInfo.getWmId()).getMenuName());
			}
			this.getPagejsonDataTables(president);
		} catch (Exception e) {
			log.error("查看网站信息列表错误！", e);
			throw new BaseException("查看网站信息列表错误！", e);
		}

		return null;

	}
	
	/**
	 * 保存网站信息初始化
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String saveWebInfoInit() throws BaseException {
		try {
			webMenus=webMenuList.getWebMenuList();
			this.getRequest().setAttribute("webMenus", webMenus);
		} catch (Exception e) {
			log("保存网站信息初始化错误！", e);
			throw new BaseException("保存网站信息初始化错误！", e);
		}
		return ADD_INIT;

	}

	/**
	 * 保存网站信息
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String saveWebInfo() throws BaseException {

		try {
			String imgUrl="",fileType="",path=getAttachmentImgPath(UPLOADDIR);
            if(file!=null){
            	InputStream in = new FileInputStream(file);   
	            String dir = GlobalSettingBase.getFilePath()+path; 
	            isExist(dir);
	            int index = fileFileName.lastIndexOf(".");
	    		if (index > -1) {
	    			fileType =fileFileName.substring(index);
	    		}
	    		fileType=fileType.toLowerCase().substring(1);
	    		Random random = new Random();
	    		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数 
				String cjrq = new SimpleDateFormat("HHmmss")
						.format(new Date());
				String fjTpName = cjrq+rannum + "." + fileType;// 文件的名字
	            File uploadFile = new File(dir, fjTpName);   
	            imgUrl=path+fjTpName;
	            OutputStream out = new FileOutputStream(uploadFile);   
	            byte[] buffer = new byte[1024 * 1024];   
	            int length;   
	            while ((length = in.read(buffer)) > 0) {   
	                out.write(buffer, 0, length);   
	            }   
	            in.close();   
	            out.close();   
	            webInfo.setLogo(imgUrl);
            }
			webInfo.setPublisher(UserRightInfoUtil.getChineseName(this.getRequest()));
			webInfo.setPublishDate(DateUtil.getCurrentDateTime());
			this.iWebInfoBiz.saveWebInfo(webInfo);
			//保存附件		
			iAttachmentBiz.saveAttachmentAndUpload(this.setUploadFile(webInfo,
					webInfo.getWiId(), AttachmentStatus.ATTACHMENT_CODE_801,
					UserRightInfoUtil.getUserName(this.getRequest())));
			
			this.getRequest().setAttribute("message", "新增成功");
			this.getRequest().setAttribute("operModule", "保存网站信息");
		} catch (Exception e) {
			log("保存网站信息错误！", e);
			throw new BaseException("保存网站信息错误！", e);
		}

		return ADD_INIT;

	}

	/**
	 * 修改网站信息初始化
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String updateWebInfoInit() throws BaseException {

		try {
			 webInfo = this.iWebInfoBiz.getWebInfo(webInfo.getWiId());

			webMenus=webMenuList.getWebMenuList();
			this.getRequest().setAttribute("webMenus", webMenus);
				
			//获取附件
			Map<String,Object> map=iAttachmentBiz.getAttachmentMap( new Attachment( webInfo.getWiId(), AttachmentStatus.ATTACHMENT_CODE_801 ) );
			webInfo.setUuIdData((String)map.get("uuIdData"));
			webInfo.setFileNameData((String)map.get("fileNameData"));
			webInfo.setFileTypeData((String)map.get("fileTypeData"));
			webInfo.setAttIdData((String)map.get("attIdData"));
			webInfo.setAttIds((String)map.get("attIds"));
		} catch (Exception e) {
			log("修改网站信息初始化错误！", e);
			throw new BaseException("修改网站信息初始化错误！", e);
		}
		return MODIFY_INIT;

	}
	/**
	 * 修改网站信息
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String updateWebInfo() throws BaseException {

		try {
			String imgUrl="",fileType="",path=getAttachmentImgPath(UPLOADDIR);
            if(file!=null){
            	InputStream in = new FileInputStream(file);   
	            String dir = GlobalSettingBase.getFilePath()+path; 
	            isExist(dir);
	            int index = fileFileName.lastIndexOf(".");
	    		if (index > -1) {
	    			fileType =fileFileName.substring(index);
	    		}
	    		fileType=fileType.toLowerCase().substring(1);
	    		Random random = new Random();
	    		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;// 获取5位随机数 
				String cjrq = new SimpleDateFormat("HHmmss")
						.format(new Date());
				String fjTpName = cjrq+rannum + "." + fileType;// 文件的名字
	            File uploadFile = new File(dir, fjTpName);   
	            imgUrl=path+fjTpName;
	            OutputStream out = new FileOutputStream(uploadFile);   
	            byte[] buffer = new byte[1024 * 1024];   
	            int length;   
	            while ((length = in.read(buffer)) > 0) {   
	                out.write(buffer, 0, length);   
	            }   
	            in.close();   
	            out.close();   
	            webInfo.setLogo(imgUrl);
            }
			this.iWebInfoBiz.updateWebInfo(webInfo);
			
			//保存附件
			iAttachmentBiz.saveAttachmentAndUpload(this.setUploadFile(webInfo,webInfo.getWiId(), AttachmentStatus.ATTACHMENT_CODE_801,UserRightInfoUtil.getUserName(this.getRequest())));
		
			// 删除附件
			iAttachmentBiz.deleteAttachments( parseAttachIds( webInfo.getAttIds() ) ) ;
			
			this.getRequest().setAttribute("message", "修改成功");
			this.getRequest().setAttribute("operModule", "修改网站信息");
		
		} catch (Exception e) {
			log("修改网站信息错误！", e);
			throw new BaseException("修改网站信息错误！", e);
		}
		return updateWebInfoInit();
	}

	/**
	 * 删除网站信息
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String deleteWebInfo() throws BaseException {
		try {
			PrintWriter out = this.getResponse().getWriter();
			String id = this.getRequest().getParameter("id");
			String[] st = id.split(",");
		
			for (int i = 0; i < st.length; i++) {
				if (st[i] != null) {
					this.iWebInfoBiz.deleteWebInfo(st[i]);
				}
			}
			String message="删除成功";
			
			this.getRequest().setAttribute("message", "删除成功");
			this.getRequest().setAttribute("operModule", "删除网站信息");
  			out.println(message);  
		} catch (Exception e) {
			log("删除网站信息错误！", e);
			throw new BaseException("删除网站信息错误！", e);
		}
		return null;

	}

	/**
	 * 查看网站明细信息
	 * 
	 * @return
	 * @throws BaseException
	 */
	public String viewWebInfoDetail() throws BaseException {

		try {
			webInfo = this.iWebInfoBiz.getWebInfo(webInfo.getWiId());
			webInfo.setAttachmentUrl(iAttachmentBiz.getAttachmentPageUrl(
					iAttachmentBiz.getAttachmentList(new Attachment(webInfo
							.getWiId(), AttachmentStatus.ATTACHMENT_CODE_801)),
					"0", this.getRequest()));
		} catch (Exception e) {
			log("查看网站明细信息错误！", e);
			throw new BaseException("查看网站明细信息错误！", e);
		}
		return DETAIL;

	}
	/**
	 * 获取附件的上传路径-相对 
	 * @param attachment
	 * @return
	 */
	public String getAttachmentImgPath(String attachmentType) {

		StringBuffer path = new StringBuffer("") ;

		String year  = DateUtil.getYear(new Date());
		String month = DateUtil.getMonth(new Date());

		// 附件存放在以时间命名的文件夹中,
		path.append( attachmentType ) ;
		path.append( year ) ;
		path.append( "/" ) ;
		path.append( month ) ;
		path.append( "/" ) ;
		
		return path.toString() ;
	}
	/**
     * 判断文件夹是否存在
     * @param path 文件夹路径
     * true 文件不存在，false 文件存在不做任何操作
     */
    public void isExist(String filePath) {
        String paths[] = filePath.split("/");
        String dir = paths[0];
        for (int i = 0; i < paths.length - 1; i++) {
                dir = dir + "/" + paths[i + 1];
                fileLocation = new File(dir);
                if (!fileLocation.exists()) {
                	fileLocation.mkdir();
                }
        }
    }

	public WebInfo getWebInfo() {
		return webInfo;
	}

	public void setWebInfo(WebInfo webInfo) {
		this.webInfo = webInfo;
	}
	public IAttachmentBiz getiAttachmentBiz() {
		return iAttachmentBiz;
	}

	public void setiAttachmentBiz(IAttachmentBiz iAttachmentBiz) {
		this.iAttachmentBiz = iAttachmentBiz;
	}

	public IWebInfoBiz getiWebInfoBiz() {
		return iWebInfoBiz;
	}

	public void setiWebInfoBiz(IWebInfoBiz iWebInfoBiz) {
		this.iWebInfoBiz = iWebInfoBiz;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

}
